import { Model, Effect } from 'dva';
import { Reducer } from 'redux';
import { getWelcomeInfo } from '@/services/welcome';

export interface WelcomeInfo {
  todayTotalOrderCount?: number;
  todayTotalSalesAmount?: number;
  yesterdayTotalSalesAmount?: number;
}

export interface WelcomePageModelState {
  welcomeInfo: WelcomeInfo;
}

export interface WelcomePageModelType extends Model {
  namespace: 'welcome';
  state: WelcomePageModelState;
  effects: {
    query: Effect;
  };
  reducers: {
    reload: Reducer<WelcomePageModelState>;
  };
}

const BrandModel: WelcomePageModelType = {
  namespace: 'welcome',
  state: {
    welcomeInfo: {},
  },

  reducers: {
    reload: (state, action) => ({
      ...state,
      welcomeInfo: action.info,
    }),
  },

  effects: {
    *query({ _payload }, { call, put }) {
      const info = yield call(getWelcomeInfo);
      yield put({
        type: 'reload',
        info,
      });
    },
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname }) => {
        if (pathname.startsWith('/index')) {
          dispatch({
            type: 'query',
          });
        }
      });
    },
  },
};

export default BrandModel;
